package com.burt.webflux;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.burt.domain.Person;
import com.burt.repository.PersonRepository;

import reactor.core.publisher.Mono;

/**
 * PersonHandler
 * 
 * @author luowei1
 * @date 2018/7/4 16:58
 */
@Component
public class PersonHandler {

    private final PersonRepository personRepository;

    @Autowired
    public PersonHandler(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    public Mono<ServerResponse> save(ServerRequest serverRequest) {
        // 在Spring Web MVC 中使用@RequestBody
        // 在Spring Web Flux 中使用ServerRequest
        //Mono<Person> 类似于Java8 中的Optional<User>
        Mono<Person> personMono = serverRequest.bodyToMono(Person.class);
        //map 相当于转化工作
        Mono<Boolean> booleanMono = personMono.map(personRepository::save);
        return ServerResponse.ok().body(booleanMono, Boolean.class);
    }
}
